<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="index.js"></script>
    <script src="./middleWares/logger.js"></script>
    <script src="./middleWares/thunk.js"></script>
    <button id="increment">+1</button>
    <span id="content">0</span>
    <button id = "decrement">-1</button>
    <span id="content2">0</span>
    <script>
        function reducer (state, action) {
            console.log(state, 'reducer')
            switch(action.type){
                case 'increment' :
                    return state + 1
                case 'decrement' :
                    return state - 1
                default :
                    return state
            }
        }
        function reducer1 (state, action) {
            switch(action.type){
                case 'increment' :
                    return state + 1
                case 'decrement' :
                    return state - 1
                default :
                    return state
            }
        }
        // 对createStore的增强
        function enhancer (createStore) {
            return function (reducer, preloadState) {
                //创建store
                let store = createStore(reducer, preloadState)
                let dispatch = store.dispatch
                // 对dispatch的扩展
                function _dispatch (action) {
                    console.log(action)
                    dispatch(action)
                }
                return {
                    ...store,
                    dispatch:_dispatch
                }

            }
        }
        // let store = createStore(reducer, {count:1}, enhancer)
        let combineReducer = combineReducers({
            count:reducer,
            count1:reducer1
        })
        let store = createStore(combineReducer, {count:1, count1:10}, applyMiddleWare(thunk, logger))
        function increment () {
            return function (dispatch) {
                dispatch({
                    type:'increment'
                })
            }
        }
        function decrement () {
            return {type:'decrement'}
        }
        const actions = bindActionCreators({increment, decrement}, store.dispatch)

        document.getElementById('increment').onclick = function () {
            // store.dispatch({type:'increment'})

            actions.increment()
        }
        document.getElementById('decrement').onclick = function () {
            // store.dispatch({type:'decrement'})
            actions.decrement()
        }
        store.subscribe(() => {
            document.getElementById('content').innerHTML = store.getState().count
        })
        store.subscribe(() => {
            document.getElementById('content2').innerHTML = store.getState().count1
        })
    </script>
</body>
</html>